<template>
    <el-autocomplete
        v-model="localValue"
        :fetch-suggestions="fetchSuggestions"
        :placeholder="placeholder"
        :clearable="clearable"
        @select="handleSelect"
        @change="handleChange"
        :disabled="disabled"
        :size="size"
        :popper-class="popperClass"
        :trigger-on-focus="triggerOnFocus"
        :debounce="debounce"
        :fetch-delay="fetchDelay"
    >
    <template v-if="customItem" #default="{ item }">
      <slot name="item" :item="item"></slot>
    </template>
  </el-autocomplete>
</template>

<script>
export default {
    name: 'ScAutoComplete',
    props: {
        value: {
            type: String,
            default: ''
        },
        placeholder: {
            type: String,
            default: '请输入搜索内容'
        },
        api: {
            type: Object,
            required: true,
            validator: (val) => {
                return typeof val === 'object' && val !== null;
            }
        },
        paramsKey: {
            type: String,
            default: 'keyword'
        },
        responseKey: {
            type: String,
            default: 'data'
        },
        rowsKey: {
            type: String,
            default: 'rows'
        },
        valueKey: {
            type: String,
            default: 'value'
        },
        clearable: {
            type: Boolean,
            default: true
        },
        disabled: {
            type: Boolean,
            default: false
        },
        size: {
        type: String,
        default: 'medium'
        },
        popperClass: {
            type: String,
            default: ''
        },
        triggerOnFocus: {
            type: Boolean,
            default: false
        },
        debounce: {
            type: Number,
            default: 300
        },
        fetchDelay: {
            type: Number,
            default: 0
        },
        customItem: {
            type: Boolean,
            default: false
        },
        additionalParams: {
            type: Object,
            default: () => ({})
        }
    },
    data() {
        return {
            localValue: this.value,
            isLoading: false,
            timer: null
        };
    },
    watch: {
        value(newVal) {
            this.localValue = newVal;
        },
        localValue(newVal) {
            this.$emit('input', newVal);
        }
    },
    methods: {
        // 处理搜索建议获取
        fetchSuggestions(queryString, cb) {
            if (!queryString && !this.triggerOnFocus) {
                cb([]);
                return;
            }

            // 清除之前的定时器
            if (this.timer) {
                clearTimeout(this.timer);
            }

            // 添加延迟，避免频繁请求
            this.timer = setTimeout(async () => {
                try {
                // 构建请求参数
                const params = {
                    [this.paramsKey]: queryString,
                    ...this.additionalParams
                };

                // 调用API
                const res = await this.api.get(params);

                if (res.code === 1 && res.data) {
                    // 获取数据数组
                    let dataArray = [];
                    if (this.rowsKey && res.data[this.rowsKey]) {
                        dataArray = res.data[this.rowsKey];
                    } else if (Array.isArray(res.data)) {
                        dataArray = res.data;
                    } else if (this.responseKey && res[this.responseKey]) {
                        dataArray = res[this.responseKey];
                    }
                    // 格式化数据为el-autocomplete需要的格式
                    const suggestions = dataArray.map(item => {
                        console.log('item :>> ', item);
                        // 如果item已经是对象且有value属性，直接返回
                        if (typeof item === 'object' && item !== null) {
                            return {
                            value: item[this.valueKey] || item.value || item,
                            ...item
                            };
                        }
                        // 否则创建包含value的对象
                        return {
                            value: item
                        };
                    });
                    cb(suggestions);
                } else {
                    cb([]);
                }
                } catch (error) {
                console.error('搜索失败:', error);
                cb([]);
                }
            }, this.fetchDelay);
        },

        // 处理选择事件
        handleSelect(item) {
            console.log('item :>> ', item);
            this.$emit('select', item);
        },

        // 处理输入变化事件
        handleChange(value) {
            this.$emit('change', value);
        },

        // 清除输入
        clear() {
            this.localValue = '';
        }
    },
    beforeUnmount() {
        // 清理定时器
        if (this.timer) {
        clearTimeout(this.timer);
        }
    }
};
</script>

<style scoped>
/* 可自定义样式 */
:deep(.el-autocomplete) {
  width: 100%;
}
</style>